package com.wsc.wisdomchinaqinghe.activitity.fourmodule;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.wsc.wisdomchinaqinghe.R;
import com.wsc.wisdomchinaqinghe.Tools.DateTimePickDialogUtil;
import com.wsc.wisdomchinaqinghe.Tools.JsonTools;
import com.wsc.wisdomchinaqinghe.Tools.Tools;
import com.wsc.wisdomchinaqinghe.activitity.baseactivity.BaseActivity;
import com.wsc.wisdomchinaqinghe.callback.ContributorView;
import com.wsc.wisdomchinaqinghe.constant.Constant;
import com.wsc.wisdomchinaqinghe.javaBean.CsLegalAidBean;
import com.wsc.wisdomchinaqinghe.javaBean.RespObj;
import com.wsc.wisdomchinaqinghe.presenter.ContributorPresenter;
import com.wsc.wisdomchinaqinghe.view.MyToast;

import java.util.Timer;
import java.util.TimerTask;

/**
 * 进入法律援助申请表
 */
public class ApplyPublishActivity extends BaseActivity implements View.OnClickListener,ContributorView {
    private ImageView regist_back;
    private TextView tv_headtitle;
    private PopupWindow popupWindow;
    private View mpopupWindowView;
    private PopupWindow popupWindowType;
    private View mpopupWindowViewType;

    private TextView tv_cancel;
    private TextView tv_man;
    private TextView tv_woman;
    private MyToast myToast;
    private Context context;
    private ContributorPresenter contributorPresenter;
    private final String APPOINTMENTFLAG="APPOINTMENTFLAG";
    private String name;
    private EditText tv_yuyuename;
    private TextView tv_sex;
    private RelativeLayout layout_sex;
    private EditText et_shenfenzhenghao;
    private TextView tv_birthday;
    private RelativeLayout layout_birthday;
    private EditText et_mingzu;
    private TextView tv_zhusuodi;
    private RelativeLayout layout_zhusuodi;
    private EditText et_phone;
    private EditText et_peoplecount;
    private TextView tv_zixunfangsi;
    private RelativeLayout layout_zixunfangsi;
    private TextView tv_zixunsixiangleibie;
    private RelativeLayout layout_zixunsixiangleibie;
    private EditText et_content;
    private Button bt_yuyue;
    private TextView tv_one;
    private TextView tv_two;
    private TextView tv_three;
    private TextView tv_four;
    private TextView tv_typecancel;
    private boolean isClick;
    private int type;
    private int subType;
    private String cid;
    private LinearLayout layout_mingshi;
    private TextView tv_laodong;
    private TextView tv_qinquan;
    private TextView tv_hunyinjiating;
    private TextView tv_other;
    private EditText et_other;
    private String leibie;
    private String source;
    private String previousId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.applypublish_layout);
        context=this;
        contributorPresenter=new ContributorPresenter(this,context);
        myToast=new MyToast(context);
        Intent intent=getIntent();
        name=intent.getStringExtra("name");
        type=intent.getIntExtra("type",1);
        subType=intent.getIntExtra("subType",0);
        cid=intent.getStringExtra("cid");
        source=intent.getStringExtra("source");
        previousId=intent.getStringExtra("previousId");
        initView();
        initPopupWindow();
        initPopupWindowType();
    }

    private void initView() {
        regist_back=(ImageView) findViewById(R.id.regist_back);
        regist_back.setOnClickListener(this);
        tv_headtitle=(TextView) findViewById(R.id.tv_headtitle);
        tv_headtitle.setText(name);
        tv_headtitle.requestFocus();
        tv_headtitle.setFocusable(true);
        tv_headtitle.setFocusableInTouchMode(true);
        tv_yuyuename=(EditText) findViewById(R.id.yuyue_name);
        tv_sex=(TextView) findViewById(R.id.tv_sex);
        layout_sex=(RelativeLayout) findViewById(R.id.layout_sex);
        layout_sex.setOnClickListener(this);
        et_shenfenzhenghao=(EditText) findViewById(R.id.tv_shenfenzhenghao);
        tv_birthday=(TextView) findViewById(R.id.tv_birthday);
        layout_birthday=(RelativeLayout) findViewById(R.id.layout_birthday);
        layout_birthday.setOnClickListener(this);
        et_mingzu=(EditText) findViewById(R.id.et_mingzu);
        tv_zhusuodi=(TextView) findViewById(R.id.tv_zhusuodi);
        layout_zhusuodi=(RelativeLayout) findViewById(R.id.layout_zhusuodi);
        layout_zhusuodi.setOnClickListener(this);
        et_phone=(EditText) findViewById(R.id.et_phone);
        et_peoplecount=(EditText) findViewById(R.id.et_peoplecount);
        tv_zixunfangsi=(TextView) findViewById(R.id.tv_zixunfangsi);
        layout_zixunfangsi=(RelativeLayout) findViewById(R.id.layout_zixunfangsi);
        layout_zixunfangsi.setOnClickListener(this);
        tv_zixunsixiangleibie=(TextView) findViewById(R.id.tv_zixunsixiangleibie);
        layout_zixunsixiangleibie=(RelativeLayout) findViewById(R.id.layout_zixunsixiangleibie);
        layout_zixunsixiangleibie.setOnClickListener(this);
        et_content=(EditText) findViewById(R.id.et_content);
        bt_yuyue=(Button) findViewById(R.id.bt_yuyue);
        bt_yuyue.setOnClickListener(this);
        layout_mingshi=(LinearLayout) findViewById(R.id.layout_mingshi);
        tv_laodong=(TextView) findViewById(R.id.tv_laodong);
        tv_qinquan=(TextView) findViewById(R.id.tv_qinquan);
        tv_hunyinjiating=(TextView) findViewById(R.id.tv_hunyinjiating);
        tv_other=(TextView) findViewById(R.id.tv_other);
        tv_laodong.setOnClickListener(this);
        tv_qinquan.setOnClickListener(this);
        tv_hunyinjiating.setOnClickListener(this);
        tv_other.setOnClickListener(this);
        et_other=(EditText) findViewById(R.id.et_other);
    }

    /**
     * 初始化popupwindow
     */
    private void initPopupWindow() {
        mpopupWindowView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.sexinfo, null);
        popupWindow = new PopupWindow(mpopupWindowView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);// 全屏显示，将内容设置在底部
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());

        tv_cancel = (TextView) mpopupWindowView.findViewById(R.id.tv_cancelsex);
        tv_cancel.setOnClickListener(this);
        tv_woman = (TextView) mpopupWindowView.findViewById(R.id.tv_takephotosex);
        tv_woman.setOnClickListener(this);
        tv_man = (TextView) mpopupWindowView.findViewById(R.id.tv_photosex);
        tv_man.setOnClickListener(this);
    }

    /**
     * 初始化popupwindow
     */
    private void initPopupWindowType() {
        mpopupWindowViewType = LayoutInflater.from(getApplicationContext()).inflate(R.layout.typeinfo, null);
        popupWindowType = new PopupWindow(mpopupWindowViewType, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);// 全屏显示，将内容设置在底部
        popupWindowType.setFocusable(true);
        popupWindowType.setBackgroundDrawable(new BitmapDrawable());


        tv_one = (TextView) mpopupWindowViewType.findViewById(R.id.tv_one);
        tv_one.setOnClickListener(this);
        tv_two = (TextView) mpopupWindowViewType.findViewById(R.id.tv_two);
        tv_two.setOnClickListener(this);
        tv_three = (TextView) mpopupWindowViewType.findViewById(R.id.tv_three);
        tv_three.setOnClickListener(this);
        tv_four = (TextView) mpopupWindowViewType.findViewById(R.id.tv_four);
        tv_four.setOnClickListener(this);
        tv_typecancel = (TextView) mpopupWindowViewType.findViewById(R.id.tv_typecancel);
        tv_typecancel.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_cancelsex:
                popupWindow.dismiss();
                break;
            // woman
            case R.id.tv_takephotosex:
                popupWindow.dismiss();
                tv_sex.setText("女");
                break;
            // man
            case R.id.tv_photosex:
                popupWindow.dismiss();
                tv_sex.setText("男");
                break;
            case R.id.layout_sex:
                View view = getWindow().peekDecorView();
                if (view != null) {
                    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService
                            (Context.INPUT_METHOD_SERVICE);
                    inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
                }
                if (!popupWindow.isShowing()) {
                    popupWindow.showAtLocation(findViewById(R.id.layout_sex), Gravity.BOTTOM, 0, 0);// 在屏幕居中，无偏移
                } else {
                    popupWindow.dismiss();
                }
                break;
            case R.id.regist_back:
                finish();
                break;
            //住所地
            case R.id.layout_zhusuodi:
                Intent intent=new Intent(context,ZhuSuoDiActivity.class);
                intent.putExtra("name","住所地(经常居住地)");
                if(tv_zhusuodi.getText().toString().trim().length()>0)
                {
                    intent.putExtra("content",tv_zhusuodi.getText().toString().trim());
                }
                startActivityForResult(intent,0);
                break;
            //咨询方式
            case R.id.layout_zixunfangsi:
                tv_one.setText("来访");
                tv_two.setText("电话");
                tv_three.setText("信函");
                tv_four.setText("网络");
                isClick=false;
                View view1 = getWindow().peekDecorView();
                if (view1 != null) {
                    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService
                            (Context.INPUT_METHOD_SERVICE);
                    inputMethodManager.hideSoftInputFromWindow(view1.getWindowToken(), 0);
                }
                if (!popupWindowType.isShowing()) {
                    popupWindowType.showAtLocation(findViewById(R.id.layout_zixunfangsi), Gravity.BOTTOM, 0, 0);// 在屏幕居中，无偏移
                } else {
                    popupWindowType.dismiss();
                }
                break;
            //咨询类别
            case R.id.layout_zixunsixiangleibie:
                isClick=true;
                tv_one.setText("刑事");
                tv_two.setText("民事");
                tv_three.setText("行政");
                tv_four.setText("其他");
                View view2 = getWindow().peekDecorView();
                if (view2 != null) {
                    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService
                            (Context.INPUT_METHOD_SERVICE);
                    inputMethodManager.hideSoftInputFromWindow(view2.getWindowToken(), 0);
                }
                if (!popupWindowType.isShowing()) {
                    popupWindowType.showAtLocation(findViewById(R.id.layout_zixunsixiangleibie), Gravity.BOTTOM, 0, 0);// 在屏幕居中，无偏移
                } else {
                    popupWindowType.dismiss();
                }
                break;
            case R.id.tv_one:
                popupWindowType.dismiss();
                if(isClick)
                {
                    tv_zixunsixiangleibie.setText(tv_one.getText());
                    layout_mingshi.setVisibility(View.GONE);
                }else
                {
                    tv_zixunfangsi.setText(tv_one.getText());
                }
                break;
            case R.id.tv_two:
                popupWindowType.dismiss();
                if(isClick)
                {
                    tv_zixunsixiangleibie.setText(tv_two.getText());
                    layout_mingshi.setVisibility(View.VISIBLE);
                }else
                {
                    tv_zixunfangsi.setText(tv_two.getText());
                }
                break;
            case R.id.tv_three:
                popupWindowType.dismiss();
                if(isClick)
                {
                    tv_zixunsixiangleibie.setText(tv_three.getText());
                    layout_mingshi.setVisibility(View.GONE);
                }else
                {
                    tv_zixunfangsi.setText(tv_three.getText());
                }
                break;
            case R.id.tv_four:
                popupWindowType.dismiss();
                if(isClick)
                {
                    tv_zixunsixiangleibie.setText(tv_four.getText());
                    layout_mingshi.setVisibility(View.GONE);
                }else
                {
                    tv_zixunfangsi.setText(tv_four.getText());
                }
                break;
            case R.id.tv_typecancel:
                popupWindowType.dismiss();
                break;
            case R.id.layout_birthday:
                DateTimePickDialogUtil dateTimePicKDialog = new DateTimePickDialogUtil(ApplyPublishActivity.this);
                dateTimePicKDialog.dateTimePicKDialog(tv_birthday);
                break;

            case R.id.bt_yuyue:
                String nameString=tv_yuyuename.getText().toString().trim();
                String sexString=tv_sex.getText().toString().trim();
                String idString=et_shenfenzhenghao.getText().toString().trim();
                String birthString=tv_birthday.getText().toString().trim();
                String peopleString=et_mingzu.getText().toString().trim();
                String addressString=tv_zhusuodi.getText().toString().trim();
                String phoneString=et_phone.getText().toString().trim();
                String initPeopleCount=et_peoplecount.getText().toString().trim();
                String zixuntypeString=tv_zixunfangsi.getText().toString().trim();
                String zixunleibieStriing=tv_zixunsixiangleibie.getText().toString().trim();
                String contentString=et_content.getText().toString().trim();
                postData(nameString,sexString,idString,birthString,peopleString,addressString,phoneString,initPeopleCount,zixuntypeString,zixunleibieStriing,contentString);
                break;

            case R.id.tv_laodong:
                leibie=tv_laodong.getText().toString().trim();
                initColor();
                tv_laodong.setTextColor(context.getResources().getColor(R.color.white));
                tv_laodong.setBackgroundColor(context.getResources().getColor(R.color.OK_color));
                break;
            case R.id.tv_qinquan:
                leibie=tv_qinquan.getText().toString().trim();
                initColor();
                tv_qinquan.setTextColor(context.getResources().getColor(R.color.white));
                tv_qinquan.setBackgroundColor(context.getResources().getColor(R.color.OK_color));
                break;
            case R.id.tv_hunyinjiating:
                leibie=tv_hunyinjiating.getText().toString().trim();
                initColor();
                tv_hunyinjiating.setTextColor(context.getResources().getColor(R.color.white));
                tv_hunyinjiating.setBackgroundColor(context.getResources().getColor(R.color.OK_color));
                break;
            case R.id.tv_other:
                leibie=tv_other.getText().toString().trim();
                initColor();
                tv_other.setVisibility(View.GONE);

                et_other.setVisibility(View.VISIBLE);
                et_other.setCursorVisible(true);
                et_other.setFocusable(true);
                et_other.setFocusableInTouchMode(true);
                et_other.requestFocus();
                Timer timer = new Timer();
                timer.schedule(new TimerTask() {

                    public void run() {
                        InputMethodManager inputManager = (InputMethodManager) et_other.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                        inputManager.showSoftInput(et_other, 0);
                    }

                }, 100);
                break;
        }
    }

    private void initColor()
    {
        tv_other.setVisibility(View.VISIBLE);
        et_other.setVisibility(View.GONE);
        tv_laodong.setTextColor(context.getResources().getColor(R.color.black99));
        tv_laodong.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.retrangepeoplecontrol));
        tv_qinquan.setTextColor(context.getResources().getColor(R.color.black99));
        tv_qinquan.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.retrangepeoplecontrol));
        tv_hunyinjiating.setTextColor(context.getResources().getColor(R.color.black99));
        tv_hunyinjiating.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.retrangepeoplecontrol));
        tv_other.setTextColor(context.getResources().getColor(R.color.black99));
        tv_other.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.retrangepeoplecontrol));

    }

    private void postData(String nameString, String sexString,String idString,String birthString,
                          String peopleString,String addressString,String phoneString,
                          String initPeopleCount,String zixuntypeString,String zixunleibieStriing,String contentString)
    {
        if(nameString.isEmpty())
        {
            myToast.showShort("名字不能为空");
            return;
        }
        if(sexString.isEmpty())
        {
            myToast.showShort("性別不能为空");
            return;
        }
        if(idString.isEmpty())
        {
            myToast.showShort("身份证号不能为空");
            return;
        }
        if(birthString.isEmpty())
        {
            myToast.showShort("出生年月不能为空");
            return;
        }
        if(peopleString.isEmpty())
        {
            myToast.showShort("民族不能为空");
            return;
        }
        if(addressString.isEmpty())
        {
            myToast.showShort("住所地不能为空");
            return;
        }
        if(phoneString.isEmpty())
        {
            myToast.showShort("电话号码不能为空");
            return;
        }
        if(initPeopleCount.isEmpty())
        {
            myToast.showShort("咨询人数不能为空");
            return;
        }
        if(zixuntypeString.isEmpty())
        {
            myToast.showShort("咨询方式不能为空");
            return;
        }
        if(zixunleibieStriing.isEmpty())
        {
            myToast.showShort("咨询事项类别不能为空");
            return;
        }
        if(contentString.isEmpty())
        {
            myToast.showShort("咨询内容不能为空");
            return;
        }
        if(!Tools.isMobile(phoneString))
        {
            myToast.showShort("电话号码格式错误");
            return;
        }

        if(idString.length()!=18)
        {
            myToast.showShort("身份证号格式错误");
            return;
        }

        String leibieName=zixunleibieStriing+":";
        if(zixunleibieStriing.equals("民事"))
        {
            if(leibie==null)
            {
                myToast.showShort("咨询事项类别“民事”下的选项未填");
                return;
            }else
            {
                leibieName+=leibie;
                if(et_other.isShown())
                {
                    String text=et_other.getText().toString().trim();
                    if(text.isEmpty())
                    {
                        myToast.showShort("咨询事项类别‘民事’下的‘其他’选项未填");
                        return;
                    }else
                    {
                        leibieName+=":";
                        leibieName+=text;
                    }
                }else
                {

                }
            }
        }else
        {

        }

        String uid= Tools.getSharedPreferencesStrings(Constant.SharePreferenceUserid,"",context);
        CsLegalAidBean csLegalAidBean=new CsLegalAidBean(nameString,sexString,idString,birthString,peopleString,addressString,phoneString,Integer.parseInt(initPeopleCount),zixuntypeString,leibieName,contentString);
        post(uid,cid,type,subType,JsonTools.objectToJsonString(csLegalAidBean));
    }

    private void post(String uid, String cid, int type, int subType, String obj) {
        if(previousId==null)
            previousId="";
        contributorPresenter.getCommunitySlSubmit(uid,cid,type,subType,obj,previousId,APPOINTMENTFLAG);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode==0 && resultCode==1)
        {
            if(data!=null)
            {
                View view = getWindow().peekDecorView();
                if (view != null) {
                    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService
                            (Context.INPUT_METHOD_SERVICE);
                    inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
                }
                String content=data.getStringExtra("content");
                tv_zhusuodi.setText(content);

            }
        }
    }


    @Override
    public void onLoadContributorStart(String flag) {
        if (flag.equals(APPOINTMENTFLAG)) {
            bt_yuyue.setEnabled(false);
        }
    }


    @Override
    public void onLoadContributorSuccess(String jsonString, String flag) {
        try {
            if (flag.equals(APPOINTMENTFLAG)) {
                RespObj respObj = JsonTools.jsonStringToObject(jsonString, RespObj.class);
                String code = respObj.getCode();
                Object object = respObj.getMessage();
                if (code.equals("200") && object != null) {
                    myToast.showShort("申请成功");
                    if(source!=null)
                    {
                        Intent intent=getIntent();
                        setResult(1,intent);
                        finish();
                    }else {
                        finish();
                    }
                }else
                {
                    myToast.showShort("操作失败");
                }
            }
        } catch (Exception e) {

        }
    }


    @Override
    public void onLoadContributorComplete(String flag) {
        if (flag.equals(APPOINTMENTFLAG)) {
            bt_yuyue.setEnabled(true);
        }
    }

    @Override
    public void onLoadContributorError(String error, String flag) {
    }



}
